/**
 *  转换ant table的sorter对象转换成分页的查询的排序字段
 * @param {object} sorter
 */
export const conventSorter = sorter => {
    const option = {};
    if(sorter)
        if(sorter.order && sorter.field) {
            // 点击排序
            option.sortField = sorter.field;
            if(sorter.order === 'descend') option.isDesc = true;
            else option.isDesc = false;
        } else {
            // 取消排序
            option.sortField = undefined;
            option.isDesc = undefined;
        }
    return option;
};
export const hasPermissions = (data, name) => Array.isArray(data) && data.length > 0 && data.some(item => item === name);

/**
 * [getObjById 根据ID获取树上对应id的对象]
 * @param  {[Array]} data [树的数据]
 * @param  {[String]} id   [需要获取的id]
 * @return {[Object]}      [对象]
 */
export const getObjById = (data, id) => {
    if(!data || !data.length || !id) return {};
    const newData = [];
    for(let i = 0; i < data.length; i++) {
        /*eslint-disable  eqeqeq*/
        if(data[i].id == id)
            return data[i];
        if(data[i].items)
            newData.push(...data[i].items);
    }
    return getObjById(newData, id);
};

/**
 * [getPathById 根据ID获取树上对应id的对象]
 * @param  {[Array]} data [树的数据]
 * @param  {[String]} id   [需要获取的id]
 * @return {[Array]}      [path]
 */
export const getPathById = (data, id) => {
    for(let i = 0; i < data.length; i++) {
        const organization = data[i];
        /*eslint-disable  eqeqeq*/
        if(organization.id == id)
            return [i];
        if(organization.items && organization.items.length > 0) {
            const path = getPathById(organization.items, id);
            if(path)
                return [i, 'items'].concat(path);
        }
    }
};

export const getTreeData = (data, props, path) => {
    const newData = [...data];
    const obj = path.reduce((a, item) => a[item], newData);
    obj.items = props;
    return newData;
};
/**
 * 计算table的 selectedRows
 * @param {*} preKeys 上一个操作 返回的 selectedKeys
 * @param {*} preRows 上一个操作 返回的 selectedRows
 * @param {*} currentKeys 本次操作 返回的 selectedKeys
 * @param {*} currentRows 本次操作 返回的 selectedRows
 * @param {*} keyIndex eg: id
 */
import difference from 'lodash/difference';
export const computeSelectedRows = (preKeys, preRows, currentKeys, currentRows, keyIndex = 'id') => {
    if(currentKeys.length === 0)
        return [];
    // 勾选
    if(currentKeys.length > preKeys.length) {
        const newKeys = difference(currentKeys, preKeys);
        const newRows = [];
        newKeys.forEach(key => {
            const row = currentRows.find(r => r[keyIndex] === key);
            if(row)
                newRows.push(row);
        });
        return [...preRows, ...newRows];
    } else if(currentKeys.length < preKeys.length) { // 取消勾选
        const deleteKeys = difference(preKeys, currentKeys);
        const newRows = preRows.filter(d => !deleteKeys.includes(d[keyIndex]));
        return newRows;
    }
    return preRows;
};
